package de.tabuma.pm.htmlcontent.controller;

import de.tabuma.pm.projectnavigation.logik.ProjectNavigationFacade;
import de.tabuma.pm.projectnavigation.entity.ProjectNavigation;
import de.tabuma.lib.tabumacontroller;
import de.tabuma.pm.*;
import de.tabuma.pm.logik.*;
import de.tabuma.pm.htmlcontent.logik.*;
import de.tabuma.pm.htmlcontent.entity.*;
import java.io.PrintWriter;
import java.util.*;
import java.util.logging.*;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.users.*;
import com.google.appengine.api.datastore.Text;

/**
 *
 * @author alefen
 */
public class controller extends tabumacontroller {

    public controller(String servlet, Hashtable parameter) {
        super(servlet,parameter);
    }

    @Override
    public void navigate(ServletContext context, HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
        String navId = (String) request.getAttribute(constants.ProjectNavigationId);
        int navIdInt = Integer.valueOf(navId);

        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        HtmlContent htmlContent = HtmlContentFacade.getFromProjectnavigationId(navIdInt);

        if(request.getParameter(constants.HtmlContentTextareaName)!=null) {
            String textarea = request.getParameter(constants.HtmlContentTextareaName);
            if(htmlContent!=null) {
                htmlContent.setText(new Text(textarea));
                HtmlContentFacade.update(htmlContent, user.getEmail());
            }
            else {
                htmlContent = new HtmlContent();
                htmlContent.setText(new Text(textarea));
                htmlContent.setProjectnavigationId(navIdInt);
                HtmlContentFacade.create(htmlContent, user.getEmail());
            }

            ProjectNavigation pn = ProjectNavigationFacade.get(navIdInt);
            pn.setNavMode(constants.ProjectNavigationHtmlContent);
            ProjectNavigationFacade.update(pn, user.getEmail());
        }

        if(htmlContent!=null) {
            request.setAttribute(constants.HtmlContentTextareaName, htmlContent.getText().getValue());
        }
        else {
            request.setAttribute(constants.HtmlContentTextareaName, "");
        }
    }


}


